<?php

namespace Portal\Domain;

use Portal\Model\Admin as AdminModel;
use Portal\Domain\AdminRole as AdminRoleDomain;
use PhalApi\Exception\BadRequestException;

class Admin
{
    public const ADMIN_STATE_NORMAL = 1;
    public const ADMIN_STATE_BANNED = 0;

    public const ADMIN_ROLE_NORMAL = 'ADMIN';
    public const ADMIN_ROLE_SUPERMAN = 'ROOT';

    public function login($username, $password)
    {
        $model = new AdminModel();
        $admin = $model->getByUsername($username);

        if (empty($admin)) {
            throw new BadRequestException("用户不存在或已被删除", 3);
            // return false;
        }

        if ($admin['status'] != self::ADMIN_STATE_NORMAL) {
            throw new BadRequestException("用户已被禁用，请联系管理员", 3);
            // return false;
        }
        $loginTimesDomain = new \Portal\Domain\AdminTimes();
        $loginTimesData = $loginTimesDomain->checkLoginTime($username);
        if ($loginTimesData['times'] >= 5 && $loginTimesData['login_time'] + 86400 >= time()) {
            $nextLoginTime = $loginTimesData['login_time'] + 86400;
            throw new BadRequestException('密码输入错误次数超过5次请于'.date('Y-m-d H:i:s', $nextLoginTime).'后再登陆', 3);
        }
        $encryptPass = $this->encryptPassword($password, $admin['salt']);
        if ($encryptPass != $admin['password']) {
            //添加密码错误次数
            $loginTimesDomain->addTimes($username);
            throw new BadRequestException("用户名或者密码错误", 3);
            // return false;
        }
        //更新错误次数
        $loginTimesDomain->fluShTimes($username);
        $exp = \PhalApi\DI()->config->get('adminapp.jwt.exp');
        // $exp = time() + $exp;
        //获取权限
        $roleDomain = new \Portal\Domain\Role();
        $roles = $roleDomain->getRoleCodes($admin['id']);
        $roleIds = $roleDomain->getRoleIds($roles);
        $payload = array(
            'id' => $admin['id'],
            'exp' => time() + $exp,
            'roles' => $roles,
            'username' => $admin['username'],
            'role_ids' => $roleIds,
        );
        $returnData['accessToken'] = \PhalApi\DI()->jwt->encodeJwt($payload);
        $returnData['tokenType'] = 'Bearer';
        $returnData['refreshToken'] = null;
        $returnData['expiresIn'] = $exp;
        return $returnData;
        //存入
    }

    // public function alterPassword($oldPassword, $newPassword)
    // {
    //     $model = new AdminModel();
    //     $admin = $model->get(\PhalApi\DI()->admin->id);

    //     if (empty($admin)) {
    //         return false;
    //     }

    //     $encryptPass = $this->encryptPassword($oldPassword, $admin['salt']);
    //     if ($encryptPass != $admin['password']) {
    //         return false;
    //     }

    //     $model->update(\PhalApi\DI()->admin->id, array('password' => $this->encryptPassword($newPassword, $admin['salt'])));

    //     \PhalApi\DI()->admin->logout();

    //     return true;
    // }
    public function resetPassword($id, $Password)
    {
        //超级管理员才有权限修改密码
        if (!\PhalApi\DI()->admin->isRoot()) {
            return false;
        }
        $model = new AdminModel();
        $admin = $model->get($id);

        if (empty($admin)) {
            return false;
        }

        // $encryptPass = $this->encryptPassword($oldPassword, $admin['salt']);
        // if ($encryptPass != $admin['password']) {
        //     return false;
        // }

        $model->update($id, array('password' => $this->encryptPassword($Password, $admin['salt'])));

        // \PhalApi\DI()->admin->logout();

        return true;
    }
    public function alertPassword($id, $oldPassword, $newPassword)
    {
        $model = new AdminModel();
        $admin = $model->get($id);

        if (empty($admin)) {
            throw new BadRequestException('用户信息不存在', 3);
        }

        $encryptPass = $this->encryptPassword($oldPassword, $admin['salt']);
        if ($encryptPass != $admin['password']) {
            throw new BadRequestException('旧密码错误', 3);
        }

        $model->update($id, array('password' => $this->encryptPassword($newPassword, $admin['salt'])));

        // \PhalApi\DI()->admin->logout();

        return true;
    }

    public function encryptPassword($password, $salt)
    {
        return md5(md5(sha1($password . $salt)));
    }
    public function createAdmin($username, $password)
    {
        $model = new AdminModel();
        $admin = $model->getByUsername($username);

        if ($admin) {
            return false;
        }
        $salt = \PhalApi\Tool::createRandStr(64);
        $newAdmin = array(
            'username' => $username,
            'nickname' => $username,
            'password' => $this->encryptPassword($password, $salt),
            'salt' => $salt,
            'status' => self::ADMIN_STATE_NORMAL,
            'create_time' => time(),
        );
        //获取用户id
        $id = $model->insert($newAdmin);
        //权限插入权限表
        $adminRoleDomain = new AdminRoleDomain();
        $adminRoleDomain->insertAdminRole($id, 'ROOT');
        return true;
    }

    // public function getAdminRoles()
    // {
    //     $model = new AdminRoleModel();
    //     return $model->getList();
    // }

    // public function getTotalNum()
    // {
    //     $model = new AdminModel();
    //     return intval($model->getTotalNum());
    // }
    public function getInfo($id)
    {

        $cacheKey = 'Admin.gteInfo.'.$id;
        $cacheData = \PhalApi\DI()->cache->get($cacheKey);
        if ($cacheData !== null) {
            return $cacheData;
        }
        $model = new AdminModel();
        //  getData($where = NULL, $whereParams = array(), $select = '*', $default = FALSE)
        $userData = $model->getData(['id' => $id], [], 'nickname,username,avatar,status,is_deleted,dept_id');

        if ($userData === false) {
            return false;
        }
        $MenuDomain = new \Portal\Domain\Menu();
        //获取菜单权限
        $menuData['perms'] = $MenuDomain->getMenuPerm();
        // $menuData['perms'] = [];
        if (is_array($userData) && !empty($userData)) {
            $returnData['userId'] = $id;
            $roleDomain = new \Portal\Domain\Role();
            $returnData['roles'] = $roleDomain->getRoleCodes($id);
            //根据用户id获取权限
            // \Portal\Model\AdminRole::notorm()->where('')
            $returnData = array_merge($returnData, $userData, $menuData);
            \PhalApi\DI()->cache->set($cacheKey, $returnData);
        }
        return $returnData;
    }
    public function flushUserInfoCache()
    {
        //更新所有管理员信息来更新权限
        $adminDatas = AdminModel::notorm()->select('id')->where(['is_deleted' => 0])->fetchAll();
        $di = \PhalApi\DI();
        foreach ($adminDatas as $adminData) {
            $cacheKey = 'Admin.gteInfo.'.$adminData['id'];
            if ($di->cache->get($cacheKey)) {
                $di->cache->delete($cacheKey);
            }
        }
    }
    public function getUserName($id)
    {
        $cacheKey = 'Admin.gteUserName.'.$id;
        $cacheData = \PhalApi\DI()->cache->get($cacheKey);

        if ($cacheData !== null) {
            return $cacheData;
        }
        $model = new AdminModel();
        $userData = $model->getData(['id' => $id], [], 'username');

        if ($userData === false) {
            return false;
        }

        \PhalApi\DI()->cache->set($cacheKey, $userData['username']);

        return $userData['username'];
    }
    public function getDepartmentUserIds($deptIds)
    {
        $model = new AdminModel();
        if (is_array($deptIds) && !empty($deptIds)) {
            $adminDatas = $model::notorm()->select('id')->where(['dept_id' => $deptIds,'is_deleted' => 0])->fetchAll();
            if ($adminDatas) {
                $ids = [];
                foreach ($adminDatas as $adminData) {
                    $ids[] = $adminData['id'];
                }
                return $ids;
            }
        }
        return [];
    }
}
